﻿using System;
using System.Diagnostics;
using Wombat.Common;
using Microsoft.Win32;
using NUnit.Framework;
using Wombat.Data.Model;

namespace Core.SystemTests.Common
{
    [TestFixture]
    public abstract class SystemTestBase
    {
        private TestingDatabaseService _testingDbServicec;

        protected WombatEntities GetEntitiesContext()
        {
            return new WombatEntities(TestingDatabaseService.EntityFrameworkConnectionString);
        }

        private void RedeployDatabase()
        {
            _testingDbServicec.DropDatabase();
            var project = ConfigurationService.GetConfigValue("DatabaseProject");
            var regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0");
            var msBuildPath = regKey.NullSafe(r => r.GetValue("MSBuildToolsPath")).NullSafe(v => v.ToString());
            ArgumentCheck.NotNull(msBuildPath, "msBuildPath");
            var configuration = "Release";
#if DEBUG
            configuration = "Debug";
#endif
            var msBuildParams =
                string.Format(
                    @"-p:Configuration={2};Platform=x86;TargetDatabase={0};TargetConnectionString=""{1}"";OutputPath=bin\{2}",
                    TestingDatabaseService.TestingDatabase,
                    TestingDatabaseService.ConnectionStringWithoutDatabase,
                    configuration);

            ExecuteMsBuild(msBuildPath + "msbuild.exe", "Deploy", msBuildParams, project);
        }

        [SetUp]
        protected virtual void OnSetup()
        {
            _testingDbServicec = new TestingDatabaseService();
            RedeployDatabase();
        }

        private void ExecuteMsBuild(string msBuildPath, string target, string par, string project)
        {
            var p = Process.Start(msBuildPath, string.Format("-target:{0} {1} {2}", target, par, project));
            p.WaitForExit();
            if (p.ExitCode != 0)
                throw new InvalidOperationException(string.Format("Error executing {0} -target:{1} {2} {3}", msBuildPath, target, par, project));
        }

    }
}
